// pages/pay/alipay/index.js
const app = getApp()
import http from '../../../utils/request.js';
import alert from '../../../utils/alert.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    authCode: "",
    chaFee: 0,
    orderNo: '',
    out_trade_no:'',
    channels: [{ channel: 'pos', text: '条码刷卡' }, { channel: 'scan', text: '扫码支付' }],
    channelIndex: 1,
    channel: 'scan',
    qrPopupvisible: false,
    qrPopupTitle: '使用支付宝扫码支付',
    qrValue: "",
    fgColor: 'black'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      orderNo: options.order_no,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindChannelChange: function (e) {
    console.log(e.detail.value)
    var channels = this.data.channels
    this.setData({
      channelIndex: e.detail.value,
      channel: channels[e.detail.value].channel
    })
  },
  scanCode:function(){
    var scanOptions={
      onlyFromCamera: false,
      scanType: 'qrCode',
      success(res) {
        if (res.scanType == "QR_CODE") {
          that.setData({
            authCode: res.result
          })
        }
      },
      fail(error) {
        util.showModel('扫描失败', error);
        console.log('request fail', error);
      }
    };
    wx.scanCode(scanOptions)
  },

  formSubmit: function (e) {
    var data = Object.assign({ app_id: app.globalData.app_id, order_no: this.data.orderNo, pay_type: 'alipay', pay_channel: this.data.channel }, e.detail.value);
    http.post(app.config.service.goOrderPay, data).then(data => {
      this.setData({
        auxOrder: data.aux_order,
      })
      switch (this.data.channel) {
        case 'scan':
          this.setData({
            qrPopupvisible: true,
            qrValue: data.qr_code
          });
          break;
        case 'pos':
          alert.alert('支付成功')
          break;
      }
    }, err => {
      alert.alert(err)
    });

  },
  queryPayResult: function (e) {
    if (!this.data.auxOrder) {
      alert.alert("请支付后再查询");
      return false;
    }
    http.get(app.config.service.getPayResult, {
      app_id: app.globalData.app_id,
      order_no: this.data.auxOrder,
    }).then(data => {
      wx.showToast({
        title: data.desc,
      })
      this.setData({
        qrPopupvisible: false
      })
    }, err => {
      alert.alert(err)
    });
  },
  onQrClose: function (e) {
    var that = this
    that.queryPayResult();
    that.setData({
      qrPopupvisible:false
    })
  }
})
